
cc.Class({
    extends: cc.Component,

    properties: {
        sl_h_score:{
            default:null,
            type:cc.Node
        },
        lay_h_score:{
            default:null,
            type:cc.Layout
        },
        allRankItemList:null,
        endRankItemList:null,
        dataList:null,
        page_length:5,
        lbHightScore:cc.Label,
        lbCurentScore:cc.Label,
        sl_end_top:{
            default:null,
            type:cc.Node
        },
        lay_end_top:{
            default:null,
            type:cc.Layout
        },
        high_score:0,
        l_time:0,
    },

    start () {
        wx.onMessage(data => {
            // console.log("---wx.onMessage："+data.message);
            switch (data.message) {
                case 'GET_TOP_BY_DLG_RANK':
                    this._getFriendCloudStorage(1);
                    break;
                case 'GET_TOP_BY_DLG_END':
                    this._getFriendCloudStorage(2);
                    break;
                case 'CLOSE_RANK_LIST':
                    this.sl_h_score.active = false;
                    break;
                case 'PAGE_UP':
                    if(this.dataList){
                        let pageNum = (this.cur_page - 1) <= 0 ? this.cur_page : (this.cur_page - 1);
                        this.showPage(pageNum);
                    }else{
                        console.log("无排行榜数据");
                    }
                    break;
                case 'PAGE_DOWN':
                    if(this.dataList){
                        // console.log("cur_page:"+this.cur_page+",dataList.length:"+this.dataList.length+","+((this.cur_page+1) * this.page_length));
                        let pageNum = ((this.cur_page+1) >= this.pageCount)  ? this.pageCount : this.cur_page+1;                        
                        this.showPage(pageNum);
                    }else{
                        console.log("无排行榜数据");
                    }
                    break;
                case 'UPDATE_HIGH_SCORE':
                    // let h_s = data.h_value;
                    let current_score = data.c_value;
                    this.lbCurentScore.string = '分数 : '+current_score;
                    // console.log('UPDATE_HIGH_SCORE--high_score:'+this.high_score+",h_s:"+h_s+",current_score:"+current_score);
                    let clear = false;
                    var date = this.getCurDate();
                    if(this.l_time == 0){
                        this.high_score = current_score;
                    }else{
                        let myDate =  new Date();
                        var day1 = new Date(this.l_time);
                        var day2 = date.dDate;
                        let diffrence = this.timeDifference(day1,day2);
                        //每周日清榜
                        //1.最后一次与今天间隔>=7天，清榜
                        //2.最后一天不是今天，且周的天数大于今天(一定是上周的)，则清榜
                        if(diffrence >= 7 || (diffrence > 0 && day2.dWeek < day1.myDate.getDay())){
                            this.high_score = current_score;
                        }
                    }
                    if(this.high_score <= current_score){
                        this.high_score = current_score;
                        this.uploadScore(this.high_score,date.dTime);
                    }
                    this.lbHightScore.string = '最高 : '+this.high_score;
                    break;
            }
        });
        this.show_start_index = 0;
        this.show_end_index = 0;
        this.cur_page  = 0;
        this.loadFinish = false;

        //加载5个Item
        this.allRankItemList = [];
        this.endRankItemList = [];
        var that = this;
        let length = 5;
        this.lay_h_score.node.removeAllChildren();
        var size = that.lay_h_score.node.getContentSize();
        let height = 90*length + 10*(length +1);
        that.lay_h_score.node.setContentSize(size.width,90*length + 10*(length +1));
        for(var i=0;i<length;i++){
            var callback = null;
            if(i == length-1){
                callback = function(){
                    that.loadFinish = true;
                };
            }
            this.addTabToNode('node_rank_item',this.allRankItemList, this.lay_h_score.node, i,callback);
        }
        //
        let count = 3;
        this.lay_end_top.node.removeAllChildren();
        var size = this.lay_h_score.node.getContentSize();
        let width = 185*count + 10*(count +1);  
        this.lay_end_top.node.setContentSize(width,size.height);
        for(var i=0;i<3;i++){
            this.addTabToNode('node_rank_item_2',this.endRankItemList, this.lay_end_top.node, i,function(){
            });
        }
    },

    onLoad(){
        this._getUserCloudStorage();
        // this._getFriendCloudStorage();
    },

    onDestroy(){
        this.allRankItemList=null;
        this.dataList=null;
    },

    //获取好友排行榜
    _getFriendCloudStorage(_type){
        this.sl_h_score.active =(_type == 1);
        this.sl_end_top.active =(_type == 2);
        wx.getFriendCloudStorage({
            keyList:['h_score'],
            success:res=>{
                // console.log("_getFriendCloudStorage-success:"+JSON.stringify(res));
                let getData  = res.data;
                if(null != getData){
                    this.dataList = this._sort(getData);
                    this.pageCount = Math.ceil(this.dataList.length/this.page_length);
                    // console.log("dataList.length:"+this.dataList.length+",pageCount:"+this.pageCount);
                     // console.log("获取好友排行榜:"+JSON.stringify(this.dataList));
                    
                    console.log("_type："+_type);
                     if(_type == 1){
                         this.showPage(1);
                     }else{
                        let count = this.dataList.length >3 ? 3 : this.dataList.length;
                        if(this.endRankItemList){
                            for(i=0;i<this.endRankItemList.length;i++){
                                //删除预设控件
                                this.endRankItemList[i].active = false;
                            }
                        }

                        let delay = this.loadFinish ? 0.01 : 0.15;
                        var that = this;
                        this.scheduleOnce(function(){
                            for(var i=0;i<count;i++){
                                var item = that.endRankItemList[i];
                                item.active = true;
                                var jsItemScore = item.getComponent('endTopItem');
                                var _dataHS = this.dataList[i];
                                jsItemScore.setData(_dataHS,i);
                            }
                        },delay);
                     }
                }
            },
            fail:res=>{
                console.log("_getFriendCloudStorage-fail:"+JSON.stringify(res));
            }
        });
    },

    showPage(pageNum){
        if(!this.dataList) return;
        if(pageNum == this.cur_page) return;
        this.cur_page  = pageNum;
        // console.log("cur_page:"+this.cur_page);
        if(this.allRankItemList){
            for(i=0;i<this.allRankItemList.length;i++){
                //删除预设控件
                this.allRankItemList[i].active = false;
            }
        }
        var start = (this.cur_page-1) * this.page_length;
        let yushu = this.dataList.length%this.page_length;
        let count = (pageNum == this.pageCount) ? (yushu ==0 ? this.page_length : yushu) : this.page_length;
        // console.log("showPage:"+pageNum+",count:"+count);
        let delay = this.loadFinish ? 0.01 : 0.15;
        var that = this;
        this.scheduleOnce(function(){
            for(var i=0;i<count;i++){
                var item_score = that.allRankItemList[i];
                item_score.active = true;
                var jsItemScore = item_score.getComponent('topItem');
                let item_id = start+i;
                var _dataHS = this.dataList[item_id];
                // console.log("showPage--item_id:"+item_id);
                jsItemScore.setData(_dataHS,item_id);
            }
        },delay);
    },

    _sort(dataList){
        var hScoreData = [];
        for(var i=0;i<dataList.length;i++){
            var kvDataList = dataList[i].KVDataList;
            // console.log("kvDataList:"+JSON.stringify(kvDataList)+",length:"+kvDataList.length);
            if(kvDataList.length==0){
                // {"key":"h_score","value":"36"},{"key":"all_km","value":"65418"}
                 dataList[i].h_score=0;
                 dataList[i].KVDataList = [
                 {key:"h_score",value:0},
                 ];
                 hScoreData[i] = dataList[i];
            }else{
                for(var j=0;j<kvDataList.length;j++){
                    var data = kvDataList[j];
                    if(data.key == 'h_score'){
                        dataList[i].h_score = Number(data.value);
                        hScoreData[i] = dataList[i];
                    }
                }
            }
        }
        function sequence_hs(a,b){
            if (a.h_score<b.h_score) {
              return 1;
            }else if(a.h_score>b.h_score){
              return -1
            }else{
             return 0;
            }    

        }
        hScoreData.sort(sequence_hs);
        return hScoreData;
    },

    //获取用户自己的数据记录
    _getUserCloudStorage(){
        var that = this;
        wx.getUserCloudStorage({
            keyList:['h_score','l_time'],
            success:res=>{
                console.log("_getUserCloudStorage-success:"+JSON.stringify(res));
                // _getUserCloudStorage-success:{
                //     "errMsg":"getUserCloudStorage:ok",
                //     "KVDataList":[
                //         {"key":"h_score","value":"21"},
                //         {"key":"all_km","value":"46048"}
                //     ]
                // }
                if(res && res.KVDataList){
                    for(var j=0;j<res.KVDataList.length;j++){
                        var data = res.KVDataList[j];
                        if(data.key == 'h_score'){
                            that.high_score = Number(data.value);
                        }
                        if(data.key == 'l_time'){
                            that.l_time = Number(data.value);
                            // console.log("l_time.value:"+data.value+","+that.l_time);
                        }
                    }
                }
                 
            },
            fail:res=>{
                console.log("_getUserCloudStorage-fail:"+JSON.stringify(res));
            }
        });
    },

        // 添加Tab预设
    addTabToNode: function (prefabPath, array, node, index, callback) {
        prefabPath = prefabPath || '';
        index = index || 0;
        if (!node) {
            cc.log("node为空");
            return;
        }
        cc.loader.loadRes(prefabPath, function (err, prefab) {
            if (err) {
                cc.error(err.message || err);
                return;
            }
            cc.log('Result should be a prefab: ' + (prefab instanceof cc.Prefab));
            //实例化
            var item = cc.instantiate(prefab);
            node.addChild(item);
            item.active = false;
            // item.setPosition(cc.p(0,index*95+45));
            array.push(item);
            if (callback) {
                callback();
            }
        });
    },
    uploadScore:function(high_s,dTime){
        // console.log("uploadScore-----h_score:"+high_s+",l_time:"+dTime);
        //同步最高分到微信
        wx.setUserCloudStorage({
            KVDataList:[
                        {key:'h_score',value:""+high_s},
                        {key:'l_time',value:""+dTime}
                        ],
            success:res =>{
                // console.log("setUserInfo---success");
                console.log(res);
            },
            fail:res =>{
                // console.log("setUserInfo---fail");
                console.log(res);
            },
        });
    },
    getCurDate(){
        let myDate =  new Date();
        let fullYear = myDate.getFullYear();    //获取完整的年份(4位,1970-????)
        let month = myDate.getMonth();       //获取当前月份(0-11,0代表1月)
        let day = myDate.getDate();        //获取当前日(1-31)
        let week = myDate.getDay();         //获取当前星期X(0-6,0代表星期天)
        let time = myDate.getTime();        //获取当前时间(从1970.1.1开始的毫秒数)

        return {dYear:fullYear,dMonth:month,dDay:day,dWeek:week,dTime:time,dDate:myDate};
    },

    timeDifference(day1,day2){
        let td = (day2 - day1) / (1000 * 60 * 60 * 24);
        console.log("时间差(天)："+td);
        let weekStr1 = this.getWeekStr(day1.getDay());
        let weekStr2 = this.getWeekStr(day2.getDay());
        console.log("最后一次--:"+day1.getFullYear()+"年-"+day1.getMonth()+"月-"+day1.getDate()+"日, 星期 "+weekStr1);
        console.log("今    天--:"+day2.getFullYear()+"年-"+day2.getMonth()+"月-"+day2.getDate()+"日, 星期 "+weekStr2);
    },
    getWeekStr(week){
        var weekStr = "";
        switch(week){
            case 0:
                weekStr = "天";
            break;
            case 1:
                weekStr = "一";
            break;
            case 2:
                weekStr = "二";
            break;
            case 3:
                weekStr = "三";
            break;
            case 4:
                weekStr = "四";
            break;
            case 5:
                weekStr = "五";
            break;
            case 6:
                weekStr = "六";
            break;
        };
        return weekStr;
    },
});
